package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.redis.service.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * redis 缓存数据初始化监听器
 *
 */
//交给Spring容器管理
@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    //spring容器初始化成功之后执行逻辑
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        System.out.println("----------------初始化对象-vo对象--start------------------------");
        //查询MongoDB中所有攻略对象
        List<Strategy> list = strategyService.findAll();
        //遍历攻略对象集合,封装vo对象
        for (Strategy strategy : list) {
            if (strategyStatisVORedisService.isStrategyVOExists(strategy.getId())) {
                continue;
            }
            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());
            //将vo对象缓存到redis中
            strategyStatisVORedisService.setStrategyStatisVO(vo);
        }
        System.out.println("-----------------初始化对象-vo对象--end--------------------------------------------");

    }

}
